package com.bajiao.common.util.jwt;

import com.bajiao.common.util.FastJsonHelper;
import com.bajiao.common.util.RsaKeyHelper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

/**
 * <P>
 * 用途:jwt 工具类
 * </p>
 *
 * @author: FanJq
 * @create: 2024-10-10
 **/
public class JWTHelper {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();

    public static String generateToken(JwtInfo jwtInfo, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(FastJsonHelper.toJSONString(jwtInfo))
                .claim("userId", jwtInfo.getUserId())
                .claim("phone", jwtInfo.getPhone())
                .claim("client", jwtInfo.getClient())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKeyFromPem(priKeyPath))
                .compact();
        return compactJws;
    }

    public static String generateTokenWY(String appid, String appsecret, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(appid)
                .claim("appid", appid)
                .claim("appsecret", appsecret)
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKeyFromPem(priKeyPath))
                .compact();
        return compactJws;
    }

    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKeyFromPem(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    public static JwtInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
        token = token.replace("Bearer ", "");
        JwtInfo jwtInfo = new JwtInfo();
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();
        if (body.get("userId") == null) {
            return null;
        }
        jwtInfo.setUserId(String.valueOf(body.get("userId")));
        if (body.get("phone") != null) {
            jwtInfo.setPhone(String.valueOf(body.get("phone")));
        }
        if (body.get("client") != null) {
            jwtInfo.setClient((Integer) body.get("client"));
            if (jwtInfo.getClient() == 4 && body.get("openId") != null) {//只有小程序登录的时候才有该值
                jwtInfo.setOpenId(String.valueOf(body.get("openId")));
            }
        }
        return jwtInfo;
    }
}
